package com.heima.wemedia.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.CompletableFuture;


@Service
public class DifyWorkflowService {

    private final RestTemplate restTemplate;
    private final String difyWorkflowUrl = "https://dify.aipfuture.com/v1/workflows/run";
    private final String apiKey = "app-wMVOzyWXN3JFoW0f55Q7OZ8p";

    public DifyWorkflowService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String generateNews(String userQuery) {
        // 1. 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);

        // 2. 构建正确的请求体结构
        Map<String, Object> requestBody = new HashMap<>();

        // 构建inputs对象，这是关键修复点
        Map<String, Object> inputs = new HashMap<>();
        inputs.put("q", userQuery);
        inputs.put("sys.files", new ArrayList<>());
        inputs.put("sys.user_id", "abc-123");
        inputs.put("sys.app_id", "483ddd35-3d32-4521-a741-0ecc124e9b0d");
        inputs.put("sys.workflow_id", "6ca733cd-12be-4aa3-8f17-8e3fd22e003e");
        inputs.put("sys.workflow_run_id", "2d3e18f4-bdce-42b9-be69-852df13eda33");

        requestBody.put("inputs", inputs);
        requestBody.put("response_mode", "blocking");
        requestBody.put("user", "abc-123");

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        try {
            // 3. 发送请求
            ResponseEntity<Map> response = restTemplate.exchange(
                    difyWorkflowUrl,
                    HttpMethod.POST,
                    requestEntity,
                    Map.class
            );

            // 4. 处理响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();

                // 根据实际响应结构调整解析逻辑
                Object dataObj = responseBody.get("data");
                if (dataObj instanceof Map) {
                    Map<String, Object> data = (Map<String, Object>) dataObj;
                    Object outputsObj = data.get("outputs");
                    if (outputsObj instanceof Map) {
                        Map<String, Object> outputs = (Map<String, Object>) outputsObj;

                        // 尝试获取text字段
                        Object textObj = outputs.get("text");
                        if (textObj instanceof String) {
                            return (String) textObj;
                        }

                        // 如果没有text字段，尝试Group1字段
                        Object group1Obj = outputs.get("Group1");
                        if (group1Obj instanceof String) {
                            return (String) group1Obj;
                        }
                    }
                }

                throw new RuntimeException("Failed to parse the response from Dify workflow. Response: " + responseBody);
            } else {
                throw new RuntimeException("Dify workflow call failed with status: " + response.getStatusCode());
            }
        } catch (Exception e) {
            throw new RuntimeException("Error generating news: " + e.getMessage(), e);
        }
    }
    private String handleSseResponse(HttpEntity<Map<String, Object>> requestEntity) {
        // 使用低级API处理SSE响应
        ResponseEntity<String> response = restTemplate.exchange(
                difyWorkflowUrl,
                HttpMethod.POST,
                requestEntity,
                String.class
        );

        if (response.getStatusCode() != HttpStatus.OK) {
            throw new RuntimeException("Dify workflow call failed with status: " + response.getStatusCode());
        }

        // 解析SSE响应数据
        return parseSseResponse(response.getBody());
    }

    private String parseSseResponse(String sseData) {
        String finalText = "";

        // 按行分割SSE数据
        String[] lines = sseData.split("\n");

        for (String line : lines) {
            // 处理data行
            if (line.startsWith("data: ")) {
                String jsonData = line.substring(6); // 移除 "data: " 前缀

                try {
                    // 解析JSON数据
                    ObjectMapper objectMapper = new ObjectMapper();
                    Map<String, Object> eventData = objectMapper.readValue(jsonData, Map.class);

                    String event = (String) eventData.get("event");

                    // 处理不同的事件类型
                    if ("node_finished".equals(event)) {
                        Map<String, Object> data = (Map<String, Object>) eventData.get("data");
                        if (data != null) {
                            Map<String, Object> outputs = (Map<String, Object>) data.get("outputs");
                            if (outputs != null) {
                                // 尝试获取text字段
                                Object textObj = outputs.get("text");
                                if (textObj instanceof String && !((String) textObj).isEmpty()) {
                                    finalText = (String) textObj;
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    // 忽略解析错误，继续处理下一行
                }
            }
        }

        return finalText;
    }

    /**
     * 流式生成新闻稿，通过SSE推送结果
     * @param userQuery 用户查询
     * @param emitter SseEmitter实例
     */
    public void streamGenerateNews(String userQuery, SseEmitter emitter) {
        try {
            // 1. 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 2. 构建支持流式响应的请求体
            Map<String, Object> requestBody = new HashMap<>();

            // 构建inputs对象
            Map<String, Object> inputs = new HashMap<>();
            inputs.put("q", userQuery);
            inputs.put("sys.files", new ArrayList<>());
            inputs.put("sys.user_id", "abc-123");
            inputs.put("sys.app_id", "483ddd35-3d32-4521-a741-0ecc124e9b0d");
            inputs.put("sys.workflow_id", "6ca733cd-12be-4aa3-8f17-8e3fd22e003e");
            inputs.put("sys.workflow_run_id", "2d3e18f4-bdce-42b9-be69-852df13eda33");

            requestBody.put("inputs", inputs);
            requestBody.put("response_mode", "streaming"); // 使用流式响应模式
            requestBody.put("user", "abc-123");

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 3. 发送请求并处理SSE响应
            handleStreamingResponse(requestEntity, emitter);

        } catch (Exception e) {
            try {
                emitter.send(SseEmitter.event().name("error").data("Failed to process request: " + e.getMessage()));
            } catch (IOException ioException) {
                // 忽略
            }
            emitter.completeWithError(e);
        }
    }

    /**
     * 处理流式响应
     * @param requestEntity 请求实体
     * @param emitter SseEmitter实例
     */
    private void handleStreamingResponse(HttpEntity<Map<String, Object>> requestEntity, SseEmitter emitter) {
        try {
            // 使用低级HTTP客户端处理流式响应
            URL url = new URL(difyWorkflowUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求头
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", "Bearer " + apiKey);
            connection.setDoOutput(true);

            // 发送请求体
            ObjectMapper objectMapper = new ObjectMapper();
            String requestBody = objectMapper.writeValueAsString(requestEntity.getBody());
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 处理响应流
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;

            while ((line = reader.readLine()) != null) {
                if (line.startsWith("data: ")) {
                    String jsonData = line.substring(6);

                    try {
                        Map<String, Object> eventData = objectMapper.readValue(jsonData, Map.class);
                        String event = (String) eventData.get("event");

                        if ("node_finished".equals(event)) {
                            Map<String, Object> data = (Map<String, Object>) eventData.get("data");
                            if (data != null) {
                                Map<String, Object> outputs = (Map<String, Object>) data.get("outputs");
                                if (outputs != null) {
                                    Object textObj = outputs.get("text");
                                    if (textObj instanceof String && !((String) textObj).isEmpty()) {
                                        // 发送生成的文本内容
                                        emitter.send(SseEmitter.event().name("content").data(textObj));
                                    }
                                }
                            }
                        } else if ("workflow_started".equals(event) || "node_started".equals(event)) {
                            // 发送状态更新
                            emitter.send(SseEmitter.event().name("status").data(event));
                        }
                    } catch (Exception e) {
                        // 忽略解析错误，继续处理下一行
                    }
                }
            }

            emitter.send(SseEmitter.event().name("complete").data("Generation completed"));
            emitter.complete();

        } catch (Exception e) {
            try {
                emitter.send(SseEmitter.event().name("error").data("Stream processing failed: " + e.getMessage()));
            } catch (IOException ioException) {
                // 忽略
            }
            emitter.completeWithError(e);
        }
    }

}
